<template>
  <view>
    <!-- 可以在这里添加商品详情展示 -->
    <view>
      <view>
        <image style="width: 100%;" mode="widthFix" :src="goodsDetail[0].goodsDetailPic"></image>
      </view>
      <view class="bottom-bar">
        <view class="price">¥ {{ money }}</view>
        <button class="purchase-btn" @click="goToBuy(goodsDetail[0].id)">立即购买</button>
      </view>
    </view>

    <!-- 底部弹窗选择镜片 -->
    <view class="modal-overlay" v-if="showLensModal" @click="closeLensModal"></view>
    <view class="lens-modal" v-if="showLensModal">
      <view class="modal-header">
        <text class="modal-title">延缓近视度数增长平均达74%</text>
      </view>
      <view class="section">
        <view class="section-title">左右眼选择</view>
        <view class="eye-select-container">
          <view class="eye-select-btn" v-for="(item, key) in lensOptions" :key="key" @click="selectEyeType(item.value)">
            <image :src="item.img" class="eye-image" mode="widthFix"></image>
          </view>
        </view>
      </view>
      <view class="section">
        <view class="section-title">镜片选择（{{ lensNumber }}）</view>
        <view class="lens-list">
          <view v-for="item in filteredFilmOptions" :key="item.goodsName"
            :class="{ active: formData.selectedFilm === item.goodsName }" @click="selectFilmOption(item)">
            <view>
              <image :src="item.goodsPic" class="lens-image" mode="widthFix"></image>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="price-info-container">
            <!-- 总价 -->
            <view class="price-item total-price">
              <text class="price-value-icon">¥</text>
              <text class="price-value total">{{ money }}</text>
            </view>
          </view>
          <button class="confirm-btn" @click="confirmLensSelection">确认支付</button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
export default {
  data() {
    return {
      goodsDetail: null,
      goodsIds: '',
      selectedSwitchKey: '',
      showLensModal: false,
      lensOptions: [
        { label: '双眼', value: 0, img: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/goods/eye-two.png' },
        { label: '左眼', value: 1, img: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/goods/eye-left.png' },
        { label: '右眼', value: 2, img: 'https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/goods/eye-right.png' },
      ],
      formData: {
        lensQuantity: 0,
        selectedFilm: 0, // 默认选中第一个镜片类型
        goodsId: 0,
      },
      money: '',
      lensNumber: 0,
    }
  },
  onLoad(options) {
    this.goodsIds = options.goodsIds
    if (this.goodsIds) {
      this.fetchGoodsDetail()
    }
  },
  computed: {
    // 计算属性：根据当前选中的眼睛类型筛选镜片选项
    filteredFilmOptions() {
      if (!this.goodsDetail || !Array.isArray(this.goodsDetail)) return [];
      
      // 根据选中的眼睛类型确定要显示的eyeType
      const selectedEyeType = this.formData.lensQuantity === 0 ? 2 : 1; // 0表示双眼，对应eyeType=2；1或2表示单眼，对应eyeType=1
      // 返回筛选后的商品选项
      return this.goodsDetail.filter(item => item.eyeType === selectedEyeType);
    }
  },
  methods: {
    fetchGoodsDetail() {
      const that = this
      this.$http.GET('/app/order/order/getGoodsListById', {
        goodsId: that.goodsIds
      }, (res) => {
        that.goodsDetail = res.data;
        console.log(that.goodsDetail)
        // that.goodsDetail.goodsDetailPic = res.data[0].goodsDetailPic
        // 设置默认选中双眼
        that.lensOptions[0].img = that.lensOptions[0].img.split('.png')[0] + '-select.png'
        
        // 根据当前选中的眼睛类型设置初始价格
        const filteredItems = that.filteredFilmOptions;
        console.log(that.filteredFilmOptions)
        // 添加空数组检查，避免Cannot read property 'goodsPic' of undefined错误
        if (filteredItems.length > 0) {
          filteredItems[0].goodsPic = filteredItems[0].goodsPic.split('.png')[0] + '-select.png'
          that.formData.selectedFilm = filteredItems[0].goodsName;
          that.formData.goodsId = filteredItems[0].id;
          that.money = filteredItems[0].goodsPrice || filteredItems[0].money;
        }
        that.lensNumber = filteredItems.length
      }, (err) => {
        console.error('请求接口失败', err);
        uni.showToast({
          title: '请求接口失败',
          icon: 'none'
        });
      })
    },
    goToBuy() {
      const that = this
      // 检查是否有switchList参数
      // if (that.goodsDetail && that.goodsDetail.switchList && Object.keys(that.goodsDetail.switchList).length > 0) {
        // 显示自定义弹窗
        that.showLensModal = true;
      // } else {
      //   // 没有switchList参数，直接创建订单
      //   that.createOrder();
      // }
    },

    // 关闭镜片选择弹窗
    closeLensModal() {
      this.showLensModal = false;
    },

    // 选择镜片选项
    selectFilmOption(item) {
      for (let i = 0; i < this.filteredFilmOptions.length; i++) {
        const element = this.filteredFilmOptions[i];
        element.goodsPic = element.goodsPic.replace('-select.png', '.png')
      }
      this.formData.selectedFilm = item.goodsName;
      item.goodsPic = item.goodsPic.split('.png')[0] + '-select.png'
      this.money = item.goodsPrice || item.money;
      this.formData.goodsId = item.id
    },

    // 选择眼睛类型
    selectEyeType(value) {
      this.formData.lensQuantity = value;
      // console.log(value)
      // 切换眼睛类型后，重置镜片选择为筛选后的第一个选项
      const filteredItems = this.filteredFilmOptions;
      this.lensOptions.forEach(item => {
        item.img = item.img.replace('-select.png', '.png')
      })
      this.lensOptions[value].img = this.lensOptions[value].img.split('.png')[0] + '-select.png'
      for (let i = 0; i < filteredItems.length; i++) {
        const element = filteredItems[i];
        element.goodsPic = element.goodsPic.replace('-select.png', '.png')
      }
      if (filteredItems.length > 0) {
        this.formData.selectedFilm = filteredItems[0].goodsName;
        this.formData.goodsId = filteredItems[0].id;
        filteredItems[0].goodsPic = filteredItems[0].goodsPic.split('.png')[0] + '-select.png'
        this.money = filteredItems[0].goodsPrice || filteredItems[0].money;
      }
      this.lensNumber = filteredItems.length
    },


    // 确认选择镜片
    confirmLensSelection() {
      if (typeof this.formData.selectedFilm !== 'undefined') {
        this.createOrderWithSwitchKey();
        this.showLensModal = false;
      } else {
        uni.showToast({
          title: '请选择镜片',
          icon: 'none'
        });
      }
    },
    // 创建订单方法（包含switchKey）
    createOrderWithSwitchKey() {
      const that = this
      let params = {
        goodsIds: that.formData.goodsId,
        filmCode: that.formData.selectedFilm,
        lensQuantity: that.formData.lensQuantity,
      }
      if (uni.getStorageSync('shopId')) {
        params.shopId = uni.getStorageSync('shopId')
      }
      this.$http.POST('/app/order/order/createOrderBuyOrUpGoods', params, (res) => {
        if (res.code === 1000) {
          that.$tools.routerTo('/pages/index/orderDetail?orderId=' + res.data.orderId, 'navigateTo', 'none')
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }, (err) => {
        console.error('请求接口失败', err);
        uni.showToast({
          title: err.message,
          icon: 'none'
        });
      });
    },
    // 原始创建订单方法
    createOrder() {
      const that = this
      let params = {
        goodsIds: this.goodsIds.split(','),
      }
      if (uni.getStorageSync('shopId')) {
        params.shopId = uni.getStorageSync('shopId')
      }
      this.$http.POST('/app/order/order/createOrderByGoodsIds', params, (res) => {
        if (res.code === 1000) {
          that.$tools.routerTo('/pages/index/orderDetail?orderId=' + res.data.orderId, 'navigateTo', 'none')
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      }, (err) => {
        console.error('请求接口失败', err);
        uni.showToast({
          title: err.message,
          icon: 'none'
        });
      });
    }
  }
}
</script>

<style>
.bottom-bar {
  position: fixed;
  bottom: 20px;
  /* 添加底部间距，使方块脱离底部 */
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #fff;
  border-radius: 20px;
  /* 调整为统一圆角 */
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  margin: 0 10px;
}

.price {
  font-size: 18px;
  color: #e64340;
}

.purchase-btn {
  background-color: #e64340;
  color: white;
  border-radius: 20px;
  width: 120px;
  margin: 0;
}

/* 底部弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 998;
}

.lens-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  z-index: 999;
  /* max-height: 80vh; */
  /* overflow-y: auto; */
}

.modal-header {
  padding: 2vw 0;
  text-align: center;
  background-color: rgba(73, 232, 224, 0.331);
  border-top-left-radius: 4vw;
  border-top-right-radius: 4vw;
  /* border-radius: 0vw; */
  /* border-bottom: 1px solid #eee; */
}

.modal-title {
  font-size: 3vw;
  font-weight: bold;
  color: rgba(8, 151, 144, 1);
}

.close-btn {
  font-size: 28px;
  color: #999;
  padding: 0 10px;
}

.lens-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 3vw;
  padding: 3vw;
  /* margin-bottom: 30vw; */
}

.lens-item {
  position: relative;
  width: 100%;
  aspect-ratio: 577 / 782;
  border: 2px solid #eee;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  transition: all 0.3s ease;
}

.lens-item.selected {
  border-color: #36b7b0;
  filter: grayscale(0%);
}

.lens-item image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.selected-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  background-color: #36b7b0;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}

.modal-footer {
    /* position: fixed; */
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px 20px;
    background-color: #fff;
    border-top: 1px solid #eee;
    z-index: 1000;
  }

  .price-info-container {
    margin-bottom: 10px;
  }

  .confirm-btn {
    background-color: #36b7b0;
    color: white;
    border-radius: 4vw;
    width: 100%;
    height: 16vw;
    line-height: 16vw;
    font-size: 5vw;
    margin: 0;
    display: block;
}

/* 左右眼选择样式 */
.eye-select-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  box-sizing: border-box;
  padding-right: 10vw;
  /* padding: 3vw 3vw; */
}

.eye-select-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1vw 0;
  margin: 0 1vw;
  transition: all 0.3s;
}

.eye-select-btn.active {
  border-color: #00BCD4;
  background-color: #e0f7fa;
}

.eye-image {
  width: 100%;
  max-width: 100%;
  height: auto;
}

.lens-image {
  width: 100%;
  height: auto;
  display: block;
  object-fit: contain;
}

.section {
    background-color: #ffffff;
    /* margin-bottom: 20rpx; */
    padding: 4vw;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  }

.section-title {
  font-size: 4vw;
  font-weight: 600;
  margin-bottom: 1vw;
  color: #333333;
}
/* 价格信息样式 */
  .price-info-container {
    /* padding: 20rpx; */
    /* padding-left: 4vw; */
  }

  .price-item {
    padding-bottom: 4vw;
  }

  .price-value {
    font-size: 28rpx;
    color: #333333;
  }

  .price-value-icon {
    font-size: 5vw;
    color: #FCB735;
    font-weight: 600;
    margin-right: 1vw;
  }

  .price-item.total-price .price-value.total {
     font-size: 8vw;
     font-weight: 600;
     color: #FCB735;
     background-clip: text;
     text-fill-color: transparent;
   }
</style>